/**
 * llmindex.io — model profile: per-domain scores, sub-metrics, run history
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * License: Proprietary — © Simon-Pierre Boucher, all rights reserved
 */
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { DemoBanner, ScoreBar, ScoreValue, formatMs, formatUsd } from '@llmindex/ui';
import { ProviderLogo } from '@/components/ProviderLogo';
import { getModelDuels, getModelProfile, getModelResponses } from '@/lib/data';

export const revalidate = 3600;
export const dynamicParams = true;

export function generateStaticParams(): Array<{ slug: string[] }> {
  return [];
}

export default async function ModelPage({ params }: { params: { slug: string[] } }) {
  const slug = params.slug.map(decodeURIComponent).join('/');
  const profile = await getModelProfile(slug);
  if (!profile) notFound();
  const [responses, duels] = await Promise.all([getModelResponses(slug), getModelDuels(slug)]);
  const responseDomains = Object.keys(responses).sort();

  return (
    <div className="space-y-8">
      <div className="space-y-2">
        <Link href="/" className="text-sm text-zinc-500 hover:text-zinc-900">
          ← Leaderboard
        </Link>
        <h1 className="flex items-center gap-3 text-2xl font-bold text-zinc-900">
          <ProviderLogo provider={profile.provider} size={30} />
          {profile.name}
        </h1>
        <p className="text-sm text-zinc-500">
          {profile.slug} · {profile.provider} · context{' '}
          {profile.contextLength?.toLocaleString() ?? '—'} · in{' '}
          {formatUsd(profile.promptPricePerM)}/1M · out {formatUsd(profile.completionPricePerM)}/1M
        </p>
      </div>

      {profile.run.kind === 'demo_seed' && <DemoBanner />}

      {profile.global && (
        <section className="rounded-lg border border-zinc-200 p-5">
          <h2 className="mb-2 text-sm uppercase tracking-wide text-zinc-500">Global Index</h2>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:gap-6">
            <span className="text-4xl font-bold tabular-nums text-emerald-600">
              {profile.global.score}
            </span>
            <div className="flex-1 space-y-1">
              <ScoreBar
                score={profile.global.score}
                scoreLow={profile.global.scoreLow}
                scoreHigh={profile.global.scoreHigh}
              />
              <p className="text-xs text-zinc-500">
                95% CI [{profile.global.scoreLow}–{profile.global.scoreHigh}] · index v
                {profile.run.indexVersion}
              </p>
            </div>
          </div>
        </section>
      )}

      <section className="space-y-3">
        <h2 className="text-xl font-semibold text-zinc-900">Per-domain scores</h2>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[56rem] text-sm">
            <thead>
              <tr className="border-b border-zinc-200 text-left text-xs uppercase tracking-wide text-zinc-500">
                <th className="py-2 pr-3">Domain</th>
                <th className="py-2 pr-3 text-right">Score (95% CI)</th>
                <th className="w-1/4 py-2 pr-3"></th>
                <th className="py-2 pr-3 text-right">Accuracy (IRT)</th>
                <th className="py-2 pr-3 text-right">Consistency</th>
                <th className="py-2 pr-3 text-right">Calibration</th>
                <th className="py-2 pr-3 text-right">Contam. Δ</th>
                <th className="py-2 pr-3 text-right">p50</th>
                <th className="py-2 pr-3 text-right">$/1k</th>
              </tr>
            </thead>
            <tbody>
              {profile.domains.map((d) => (
                <tr key={d.domain} className="border-b border-zinc-100">
                  <td className="py-2 pr-3 capitalize">
                    <Link
                      href={`/leaderboard/${d.domain}`}
                      className="hover:text-emerald-600"
                    >
                      {d.domain.replaceAll('_', ' ')}
                    </Link>
                  </td>
                  <td className="py-2 pr-3 text-right">
                    <ScoreValue score={d.score} scoreLow={d.scoreLow} scoreHigh={d.scoreHigh} />
                  </td>
                  <td className="py-2 pr-3">
                    <ScoreBar score={d.score} scoreLow={d.scoreLow} scoreHigh={d.scoreHigh} />
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {d.subMetrics?.accuracy_irt?.toFixed(3) ?? '—'}
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {d.subMetrics?.consistency?.toFixed(2) ?? '—'}
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {d.subMetrics?.calibration?.toFixed(2) ?? '—'}
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {d.subMetrics?.contamination_delta?.toFixed(3) ?? '—'}
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {formatMs(d.subMetrics?.latency_p50)}
                  </td>
                  <td className="py-2 pr-3 text-right tabular-nums text-zinc-600">
                    {formatUsd(d.subMetrics?.cost_per_1k_items)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {responseDomains.length > 0 && (
        <section className="space-y-3">
          <h2 className="text-xl font-semibold text-zinc-900">Every answer, every test</h2>
          <p className="text-sm text-zinc-500">
            Full transparency: the model&apos;s latest graded answer on every instantiated item of
            the current index version. Answer keys never leave the server; anchor-item prompts are
            withheld to protect the longitudinal subset.
          </p>
          {responseDomains.map((domain) => {
            const rows = responses[domain]!;
            const nCorrect = rows.filter((r) => r.correct === true).length;
            return (
              <details key={domain} className="rounded-xl border border-zinc-200">
                <summary className="cursor-pointer select-none px-4 py-3 text-sm font-medium capitalize text-zinc-800 hover:bg-zinc-50">
                  {domain.replaceAll('_', ' ')}{' '}
                  <span className="ml-2 text-xs tabular-nums text-zinc-500">
                    {nCorrect}/{rows.length} correct
                  </span>
                </summary>
                <div className="max-h-[32rem] space-y-2 overflow-y-auto border-t border-zinc-200 p-3">
                  {rows.map((r, i) => (
                    <div key={i} className="rounded-lg border border-zinc-100 bg-white p-3 text-xs">
                      <div className="flex flex-wrap items-center gap-2">
                        <span
                          className={
                            'rounded px-1.5 py-0.5 font-semibold ' +
                            (r.correct === true
                              ? 'bg-emerald-100 text-emerald-700'
                              : r.correct === false
                                ? 'bg-red-100 text-red-700'
                                : 'bg-zinc-200 text-zinc-600')
                          }
                        >
                          {r.correct === true ? 'correct' : r.correct === false ? 'wrong' : r.error ?? 'unscored'}
                        </span>
                        <span className="text-zinc-500">{r.templateId}</span>
                        {r.isAnchor && <span className="rounded bg-amber-100 px-1.5 py-0.5 text-amber-700">anchor</span>}
                        <span className="ml-auto tabular-nums text-zinc-500">
                          conf {r.confidence != null ? Math.round(r.confidence * 100) + '%' : '—'} ·{' '}
                          {formatMs(r.latencyMs)} · {formatUsd(r.costUsd)} · {r.tokensOut ?? '—'} tok
                        </span>
                      </div>
                      {r.prompt && (
                        <details className="mt-2">
                          <summary className="cursor-pointer text-zinc-500">question</summary>
                          <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-zinc-100 p-2 text-[11px] text-zinc-600">
                            {r.prompt}
                          </pre>
                        </details>
                      )}
                      <div className="mt-2">
                        <span className="text-zinc-500">model answer: </span>
                        <code className="break-all text-zinc-800">{r.answer ?? '(none extracted)'}</code>
                      </div>
                    </div>
                  ))}
                </div>
              </details>
            );
          })}
        </section>
      )}

      {duels.length > 0 && (
        <section className="space-y-3">
          <h2 className="text-xl font-semibold text-zinc-900">Judge-rated duels</h2>
          <p className="text-sm text-zinc-500">
            Pairwise duels (writing, safety, SVG logo design) rated by a cross-provider judge
            panel with recorded position swaps.
          </p>
          <div className="space-y-2">
            {duels.map((d, i) => (
              <details key={i} className="rounded-xl border border-zinc-200">
                <summary className="cursor-pointer select-none px-4 py-3 text-sm hover:bg-zinc-50">
                  <span
                    className={
                      'mr-2 rounded px-1.5 py-0.5 text-xs font-semibold ' +
                      (d.outcome === 'win'
                        ? 'bg-emerald-100 text-emerald-700'
                        : d.outcome === 'loss'
                          ? 'bg-red-100 text-red-700'
                          : 'bg-zinc-200 text-zinc-600')
                    }
                  >
                    {d.outcome}
                  </span>
                  <span className="capitalize text-zinc-700">{d.domain.replaceAll('_', ' ')}</span>
                  <span className="text-zinc-500"> vs {d.opponent} · judge {d.judge}</span>
                  {d.positionSwapped && <span className="ml-1 text-xs text-zinc-400">(positions swapped)</span>}
                </summary>
                <div className="space-y-2 border-t border-zinc-200 p-3 text-xs">
                  <div>
                    <span className="text-zinc-500">task: </span>
                    <span className="text-zinc-700">{d.prompt.slice(0, 400)}</span>
                  </div>
                  {d.myResponseExcerpt && (
                    <pre className="max-h-48 overflow-auto whitespace-pre-wrap rounded bg-zinc-100 p-2 text-[11px] text-zinc-600">
                      {d.myResponseExcerpt}
                    </pre>
                  )}
                </div>
              </details>
            ))}
          </div>
        </section>
      )}

      <section className="space-y-3">
        <h2 className="text-xl font-semibold text-zinc-900">Run history</h2>
        <ul className="space-y-1 text-sm text-zinc-600">
          {profile.runHistory.map((h) => (
            <li key={h.runId} className="flex gap-4">
              <span className="tabular-nums">{new Date(h.createdAt).toISOString().slice(0, 10)}</span>
              <span>v{h.indexVersion}</span>
              <span className="text-zinc-500">{h.kind}</span>
              <span className="tabular-nums text-zinc-800">{h.score ?? '—'}</span>
            </li>
          ))}
        </ul>
      </section>
    </div>
  );
}
